package util

import (
	"bufio"
	"fmt"
	ffmpeg_go "github.com/u2takey/ffmpeg-go"
	"io/ioutil"
	"log"
	"math"
	"mp4/entity"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"time"
)

const (
	SLEEP_VALUE = 300
)

func FFmpegDownload(responseEntity entity.ResponseEntity, configEntity entity.DownloadEntity, title string) (bool, string) {
	//start := time.Now()
	if len(strings.TrimSpace(responseEntity.M3u8)) == 0 {
		return false, ""
	}
	mkdirPath := CombinationFielPath(configEntity.FileDirPath, title+configEntity.AudioType)
	var paths []string
	if ExistsFile(mkdirPath, configEntity) {
		paths = append(paths, mkdirPath)
		return true, mkdirPath
	}
	timOut := fmt.Sprintf("%d", configEntity.MaxNum*10000)

	val := fmt.Sprintf("%d", configEntity.MaxNum*10000*5)
	log.Println(mkdirPath, responseEntity.M3u8)

	err := ffmpeg_go.Input(strings.TrimSpace(responseEntity.M3u8)).
		Output(strings.TrimSpace(mkdirPath), ffmpeg_go.KwArgs{"timeout": timOut, "rw_timeout": val, "allowed_extensions": "ALL", "qscale": "0",
			"b:v": "0", "c:v": "copy"}).OverWriteOutput().Run()
	if nil != err {
		log.Println(err)
		return false, mkdirPath
	}
	flag, _ := ValidateFileSize(mkdirPath, configEntity, paths)
	if flag {
		//sleepAndPrint(SLEEP_VALUE, start)

		return true, mkdirPath
	}

	return false, mkdirPath
}

func cmdExit(cmd *exec.Cmd) {
	defer func() { cmd = nil }()
	exec.Command("exit")
	cmd.Run()

}

func SysnthesisTsToMp4(path string, configEntity entity.DownloadEntity, filePath string) (bool, string) {

	cmd := exec.Command(strings.TrimSpace(configEntity.FFmpeg), "-f", "concat", "-i", path, "-c", "copy", filePath)
	defer func() { cmdExit(cmd) }()
	err := cmd.Run()

	if nil != err {
		time.Sleep(15 * time.Second)
		fmt.Println(filePath, "[", path, "]合成错误:", err)
		return false, filePath
	}
	return true, filePath
}

func SysnthesisTsZipToMp4(title string, configEntity entity.DownloadEntity, filePath string, targetPath string) (bool, string) {

	flag, filePath := ZipOf7Z(title, filePath, configEntity)
	if flag {
		//err := ffmpeg_go.Input(filePath).Output(targetPath, ffmpeg_go.KwArgs{"r": "25", "c:v": "libx265", "qscale": "0", "q:v": "1", "c:a": "aac", "b:v": "20000k", "vf": "scale=2048:-1"}).OverWriteOutput().Run()
		//err := ffmpeg_go.Input(filePath).Output(targetPath, ffmpeg_go.KwArgs{"r": "25", "qscale": "0", "q:v": "1", "c:a": "aac", "b:v": "20000k", "vf": "scale=2048:-1"}).OverWriteOutput().Run()
		//err := ffmpeg_go.Input(filePath).Output(targetPath, ffmpeg_go.KwArgs{"c:v": "libx265"}).OverWriteOutput().Run()
		//if nil != err {
		//	log.Println(err)
		//	return false, targetPath
		//}
		flag := false
		if configEntity.ZipConvert == nil || len(configEntity.ZipConvert) == 0 {
			flag = CopyFfmpeg(filePath, targetPath)
		} else {
			//var result map[string]interface{}
			//
			//err := json.Unmarshal(configEntity.ZipConvert, &result)
			//if err != nil {
			//	panic(err)
			//}

			err := ffmpeg_go.Input(filePath, ffmpeg_go.KwArgs{"hwaccel": "cuda"}).Output(targetPath, configEntity.ZipConvert).OverWriteOutput().Run()
			if nil != err {
				log.Println(err)
				return false, targetPath
			}
			return true, targetPath
		}

		return flag, targetPath
	}
	return false, targetPath
}

func ConvertToMpt(path string, filePath string, config entity.DownloadEntity) (bool, string) {
	err := ffmpeg_go.Input(path, ffmpeg_go.KwArgs{"hwaccel": "cuda"}).
		Output(filePath, ffmpeg_go.KwArgs{"c": "copy"}).OverWriteOutput().Run()

	if nil != err {
		log.Println(err)
		return false, filePath
	}

	return true, filePath
}

func SegmentationTs(title string, path string, config entity.DownloadEntity, targetFile string) (bool, string) {
	tsPath := config.FileDirPath + "/" + targetFile
	tsPaths := switchNameType(tsPath, ".ts")
	removeFile(tsPaths)

	err := ffmpeg_go.Input(config.FileDirPath+"/"+title, ffmpeg_go.KwArgs{"hwaccel": "cuda"}).
		Output(tsPath+"/"+"%08d.ts", ffmpeg_go.KwArgs{"c": "copy", "map": 0, "f": "segment", "segment_time": 1, "segment_format": "mpegts", "qscale": "0"}).OverWriteOutput().Run()

	if nil != err {
		log.Println(err)
		return false, tsPath
	}

	return true, tsPath
}

func SegmentationTs1(title string, path string, config entity.DownloadEntity, targetFile string) (bool, string) {
	tsPath := path + "/" + targetFile
	tsPaths := switchNameType(tsPath, ".ts")
	removeFile(tsPaths)

	err := ffmpeg_go.Input(config.FileDirPath+"/"+title, ffmpeg_go.KwArgs{"hwaccel": "cuda"}).
		Output(tsPath+"/"+"%08d.ts", ffmpeg_go.KwArgs{"c": "copy", "map": 0, "f": "segment", "segment_time": 1, "segment_format": "mpegts", "qscale": "0"}).OverWriteOutput().Run()

	if nil != err {
		log.Println(err)
		return false, tsPath
	}

	return true, tsPath
}

func SegmentationJPG(filePath string, title string, config entity.DownloadEntity) []string {
	imagesPath := switchName(filePath, title)
	removeFile(imagesPath)
	filePath = strings.ReplaceAll(filePath, "\\", "/")
	var imagePath = filePath
	str := title[0:strings.LastIndex(title, ".")]
	err := ffmpeg_go.Input(filePath+"/"+title, ffmpeg_go.KwArgs{"hwaccel": "cuda"}).
		Output(imagePath+"/"+str+"_%05d.jpg", ffmpeg_go.KwArgs{"r": "1", "f": "image2"}).OverWriteOutput().Run()

	if nil != err {
		log.Println(err)
		return switchName(filePath, title)
	}

	return switchName(filePath, title)
}

func CopyFfmpeg(source string, target string) bool {
	err := ffmpeg_go.Input(source, ffmpeg_go.KwArgs{"hwaccel": "cuda"}).
		Output(target, ffmpeg_go.KwArgs{"c:v": "copy", "b:v": "0", "qscale": "0"}).OverWriteOutput().Run()
	if nil != err {
		log.Println(err)
		return false
	}

	return true
}
func GetVideoDuration(filePath string) (int, bool) {
	cmd := exec.Command("ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filePath)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Println(err)
		return -1, false
	}

	if err := cmd.Start(); err != nil {
		log.Println(err)
		return -1, false
	}

	scanner := bufio.NewScanner(stdout)
	var durationStr string
	for scanner.Scan() {
		durationStr = scanner.Text()
	}

	if err := scanner.Err(); err != nil {
		log.Println(err)
		return -1, false
	}

	if err := cmd.Wait(); err != nil {
		log.Println(err)
		return -1, false
	}

	duration, err := strconv.ParseFloat(durationStr, 64)
	if err != nil {
		log.Println(err)
		return int(math.Ceil(duration)), false
	}
	return int(math.Ceil(duration)), true
}

func Segmentation(mp4FilePath string, timeResult int, config entity.DownloadEntity, playEntity entity.PlayListEntity, targetPath string) (bool, string) {
	countNum := 0
	val := timeResult % config.Time
	if val == 0 {
		countNum = timeResult / config.Time
	} else {
		countNum = timeResult/config.Time + 1
	}
	if ExistsDir(targetPath) {
		err := os.MkdirAll(targetPath, os.ModePerm)
		if err != nil {
			log.Println(err)
			return false, targetPath
		}
	}

	//var paths []string
	for i := 0; i < countNum; i++ {
		startTime := i * config.Time
		endTime := (i + 1) * config.Time

		startTimeStr := convertSecond(startTime)
		endTimeStr := convertSecond(endTime)

		name := targetPath + "/" + playEntity.TitleStr + "_" + strconv.Itoa(i) + ".mp4"

		err := ffmpeg_go.Input(mp4FilePath, ffmpeg_go.KwArgs{"ss": startTimeStr, "to": endTimeStr}).Output(name, ffmpeg_go.KwArgs{"vsync": "cfr", "c:v": "copy", "qscale": "0"}).OverWriteOutput().Run()
		if nil != err {
			log.Println(err)
			return false, targetPath
		}
		//content := fmt.Sprintf(config.HtmlContent, playEntity.TitleStr+"_"+strconv.Itoa(i))
		//flag, _ := WriterTxtTip(targetPath+"/"+playEntity.TitleStr+"_"+strconv.Itoa(i)+".txt", content)
		//if flag {
		//	paths = append(paths, fmt.Sprintf(config.AuthSubmit, name))
		//}
	}

	return true, targetPath
}

func AddBackMusic(filePath string, config entity.DownloadEntity, title string) bool {
	filePath = strings.ReplaceAll(filePath, "\\", "/")
	files, _ := ioutil.ReadDir(filePath)
	htmlContentPath := config.FileDirPath + "/htmlContent"
	if ExistsDir(htmlContentPath) {
		err := os.MkdirAll(htmlContentPath, os.ModePerm)
		if err != nil {
			log.Println(err)
			return false
		}
	}

	var paths []string
	for _, f := range files {
		if strings.HasSuffix(f.Name(), ".mp4.mp4.mp4") {
			continue
		} else if strings.HasSuffix(f.Name(), ".mp4.mp4") {
			sourcePath := filePath + "/" + f.Name()
			targetPath := filePath + "/" + f.Name() + ".mp4"
			timeVal, _ := GetVideoDuration(sourcePath)
			if timeVal < 0 {
				return false
			}
			timeStr := convertSecond(timeVal + 1)

			exces := []string{config.FFmpeg, "-i", sourcePath, "-i", config.BackMusicPath, "-filter_complex", "[1:a]aloop=loop=-1:size=2e+09[out];[out][0:a]amix", "-ss", "0", "-t", "timeStr", "-vcodec", "libx265", "-b:v", "0", targetPath}

			cmd := exec.Command(config.FFmpeg,
				"-hwaccel", "cuda",
				"-i", sourcePath,
				"-i", config.BackMusicPath,
				"-filter_complex", "[1:a]aloop=loop=-1:size=2e+09[out];[out][0:a]amix",
				"-ss", "0",
				"-t", timeStr,
				"-vcodec", "libx265",
				"-b:v", "0",
				targetPath,
				"-y")

			log.Println(exces)
			err := cmd.Run()
			if err != nil {
				log.Println(err)
			} else {
				paths = WriteTip(config, f.Name(), targetPath, paths)

				//os.Remove(sourcePath)
			}
		}

	}
	WriterArrayTip(htmlContentPath+"/"+title+".txt", paths)
	return true
}

func AddBackMusic1(sourcePath string, config entity.DownloadEntity, target string) bool {

	if IsEmpty(config.BackMusicPath) {
		return true
	}
	timeVal, _ := GetVideoDuration(sourcePath)
	if timeVal < 0 {
		return false
	}
	timeStr := convertSecond(timeVal + 1)

	cmd := exec.Command(config.FFmpeg,
		"-hwaccel", "cuda",
		"-i", sourcePath,
		"-i", config.BackMusicPath,
		"-filter_complex", "[1:a]aloop=loop=-1:size=2e+09[out];[out][0:a]amix",
		"-ss", "0",
		"-t", timeStr,
		"-vcodec", "libx265",
		"-b:v", "0",
		"-qscale", "0",
		target,
		"-y")

	err := cmd.Run()
	if err != nil {
		log.Println(err)
		return false
	}
	return true
}

func WriteTip(config entity.DownloadEntity, name string, targetPath string, paths []string) []string {
	content := fmt.Sprintf(config.HtmlContent, name)
	txtPath := strings.ReplaceAll(targetPath, ".mp4", ".txt")
	flag, _ := WriterTxtTip(txtPath, content)
	if flag {
		paths = append(paths, fmt.Sprintf(config.AuthSubmit, targetPath))
	}
	return paths
}
func convertSecond(time int) string {
	if time < 60 {
		return combationTime(0, 0, time)
	}

	minute := time / 60
	if minute < 60 {
		second := time - minute*60
		return combationTime(0, minute, second)
	}
	hour := minute / 60
	time1 := time - hour*60*60
	minute = time1 / 60

	time1 = time1 - minute*60

	return combationTime(hour, minute, time1)
}

func combationTime(hour int, minute int, second int) string {
	hourStr := formatTitle1(hour, 2)
	minuteStr := formatTitle1(minute, 2)
	secondStr := formatTitle1(second, 2)

	return hourStr + ":" + minuteStr + ":" + secondStr
}

func WatermarkFun(path string, config entity.DownloadEntity) bool {
	files, _ := ioutil.ReadDir(path)

	if IsEmpty(config.Watermark) {
		return true
	}

	for _, f := range files {
		if strings.HasSuffix(f.Name(), ".ts.ts.ts") {
			continue
		} else if strings.HasSuffix(f.Name(), ".ts.ts") {
			continue
		} else if strings.HasSuffix(f.Name(), ".ts") {

			sourcePath := path + "/" + f.Name()
			targetPath := path + "/" + f.Name() + ".ts"
			if IsEmpty(config.Watermark) {
				CopyFfmpeg(sourcePath, targetPath)
			} else {
				//err := ffmpeg_go.Input(sourcePath).Output(targetPath, ffmpeg_go.KwArgs{"i": "E:\\temp\\download\\3.png", "filter_complex": "\"overlay=W-w-10:H-h-10:alpha=0.9\"", "acodec": "copy", "vcodec": "h264", "b:v": "0"}).OverWriteOutput().Run()
				//if nil != err {
				//	log.Println(err)
				//} else {
				//	os.Remove(sourcePath)
				//}

				cmd := exec.Command(config.FFmpeg,
					"-hwaccel", "cuda",
					"-i", sourcePath,
					"-i", config.Watermark,
					"-filter_complex", "overlay=W-w-10:H-h-10",
					"-acodec", "copy",
					"-qscale", "0",
					"-vcodec", "h264",
					"-b:v", "0",
					targetPath,
					"-y")

				err := cmd.Run()
				if err != nil {
					log.Println(sourcePath, err)
				} else {
					os.Remove(sourcePath)
				}
			}
		}
	}
	return true
}

func MerryGoRoundFun(path string, config entity.DownloadEntity, title string) bool {
	files, _ := ioutil.ReadDir(path)
	htmlContentPath := config.FileDirPath + "/htmlContent"
	if ExistsDir(htmlContentPath) {
		err := os.MkdirAll(htmlContentPath, os.ModePerm)
		if err != nil {
			log.Println(err)
			return false
		}
	}

	var paths []string
	for _, f := range files {
		if strings.HasSuffix(f.Name(), ".mp4.mp4.mp4") {
			continue
		}
		if strings.HasSuffix(f.Name(), ".mp4.mp4") {
			continue
		} else if strings.HasSuffix(f.Name(), ".mp4") {
			sourcePath := path + "/" + f.Name()
			targetPath := path + "/" + f.Name() + ".mp4"

			//err := ffmpeg_go.Input(sourcePath).Output(targetPath, ffmpeg_go.KwArgs{"i": "E:\\temp\\download\\3.png", "filter_complex": "\"overlay=W-w-10:H-h-10:alpha=0.9\"", "acodec": "copy", "vcodec": "h264", "b:v": "0"}).OverWriteOutput().Run()
			//if nil != err {
			//	log.Println(err)
			//} else {
			//	os.Remove(sourcePath)
			//}
			exces := []string{config.FFmpeg, "-i", sourcePath, "-i", config.MerryGoRound, "-c:v", "copy", "-crf", "25", "-pix_fmt", "yuv420p", "-vcodec", "libx265", "-b:v", "0", "-filter_complex", "overlay=x='if(gte(t,2), -w+(t-2)*20, NAN)':y=0", targetPath}

			cmd := exec.Command(config.FFmpeg,
				"-hwaccel", "cuda",
				"-i", sourcePath,
				"-i", config.MerryGoRound,
				"-c:v", "copy",
				"-crf", "25",
				"-pix_fmt", "yuv420p",
				"-vcodec", "libx265",
				"-qscale", "0",
				"-b:v", "0",
				"-filter_complex", "overlay=x='if(gte(t,2), -w+(t-2)*20, NAN)':y=0",
				targetPath,
				"-y")

			log.Println(exces)
			var err error
			if IsNotEmpty(config.MerryGoRound) {
				err = cmd.Run()
			} else {
				CopyFfmpeg(sourcePath, targetPath)
			}

			if err != nil {
				log.Println(err)
			} else {
				content := fmt.Sprintf(config.HtmlContent, f.Name())
				txtPath := strings.ReplaceAll(targetPath, ".mp4", ".txt")
				flag, _ := WriterTxtTip(txtPath, content)
				if flag {
					paths = append(paths, fmt.Sprintf(config.AuthSubmit, targetPath))
				}
			}
		}

	}
	WriterArrayTip(htmlContentPath+"/"+title+".txt", paths)
	return true
}

func ValidateFileFFmpeg(path string, config entity.DownloadEntity) bool {
	cmd := exec.Command(config.FFmpeg,
		"-hwaccel", "cuda",
		"-i", path,
		"-v", "error",
		"-map", "0:1",
		"-f", "null",
		"-")

	err := cmd.Run()
	if err != nil {
		log.Println(path, err)
		return false
	}
	return true

}

func Conver(path string, x int, y int, w int, h int, config entity.DownloadEntity) bool {
	target := path + ".ts"
	vf := "drawbox=x=%d:y=%d:w=%d:h=%d:color=#eeeeee@0.85:t=fill"
	vf = fmt.Sprintf(vf, x, y, w, h)
	cmd := exec.Command(config.FFmpeg,
		"-hwaccel", "cuda",
		"-i", path,
		"-vf", vf,
		"-c:v", "libx265",
		"-crf", "18",
		target)

	err := cmd.Run()
	if err != nil {
		log.Println(err)
		return false
	}

	CopyFfmpeg(target, path)
	os.Remove(target)
	return true

}

func Convert4K(source string, target string) bool {
	err := ffmpeg_go.Input(source, ffmpeg_go.KwArgs{"hwaccel": "cuda"}).
		Output(target, ffmpeg_go.KwArgs{"vf": "scale=3840:2160", "preset": "slow", "crf": "18", "c:a": "copy", "vcodec": "libx265", "qscale": "0"}).OverWriteOutput().Run()
	if nil != err {
		log.Println(err)
		return false
	}

	return true
}

func ConvertTo2K(source string, target string, config entity.DownloadEntity) bool {
	cmd := exec.Command(config.FFmpeg,
		"-hwaccel", "cuda",
		"-i", source,
		"-r", "25",
		"-qscale", "0",
		"-q:v", "1",
		"-c:a", "aac",
		"-b:v", "20000k",
		"-vf", "scale=2048:-1",
		target,
		"-y")

	err := cmd.Run()

	if err != nil {
		log.Println(err)
		return false

	}
	//err := ffmpeg_go.Input(source, ffmpeg_go.KwArgs{"hwaccel": "cuda", "r": "25", "qscale": "0", "q:v": "1", "c:a": "aac", "b:v": "20000k", "vf": "scale=2048:-1"}).Output(target)
	//if err != nil {
	//	log.Println(err)
	//	return false
	//
	//}
	return true
}

func Synthesis(path string, configEntity entity.DownloadEntity) (bool, []string) {
	files, _ := ioutil.ReadDir(path)
	var paths []string
	for _, f := range files {

		flg := true
		var targetPath string

		if strings.HasSuffix(f.Name(), ".2.mp4") {
			paths = append(paths, fmt.Sprintf(configEntity.AuthSubmit, path+"/"+f.Name()))
			continue
		} else if strings.HasSuffix(f.Name(), ".mp4.mp4.mp4") {
			continue
		} else if strings.HasSuffix(f.Name(), ".zip.mp4") {
			continue
		} else if strings.HasSuffix(f.Name(), ".3.mp4") {
			continue
		} else if strings.HasSuffix(f.Name(), ".mp4.mp4") {
			source := path + "/" + f.Name()
			fileName := strings.ReplaceAll(f.Name(), ".mp4", "")
			//fileName1 := strings.ReplaceAll(f.Name(), ".mp4", "")
			filePath := path + "/" + fileName

			if ExistsDir(filePath) {
				os.MkdirAll(filePath, os.ModePerm)
			}
			ConvertTo2K(source, source+".mp4", configEntity)
			flg = segmentationToTs(source+".mp4", filePath, "000")
			//segmentationToTs(source, filePath, "000")

			fs, _ := ioutil.ReadDir(filePath)
			index := 0
			for _, item := range fs {
				name1 := item.Name()[0:3]
				if name1 == "000" {
					name2 := "002"

					name4 := fmt.Sprintf("%s/%s%s", filePath, name2, item.Name())

					CopyFfmpeg(filePath+"/"+item.Name(), name4)
					if index > 1 {
						name5 := fmt.Sprintf("%s/%s", filePath, item.Name())
						os.Remove(name5)
					}
					index++
				}
			}
			if !IsEmpty(configEntity.BeforeMp4) {
				//ConvertTo2K(configEntity.BeforeMp4, configEntity.BeforeMp4+".2.mp4", configEntity)
				flg = segmentationToTs(configEntity.BeforeMp4+".2.mp4", filePath, "001")
			}

			if flg {
				ConvertTo2K(source, source+".mp4", configEntity)
				flg = segmentationToTs(source+".mp4", filePath, "002")
			}

			if !IsEmpty(configEntity.EndMp4) && flg {
				//	ConvertTo2K(configEntity.EndMp4, configEntity.EndMp4+".2.mp4", configEntity)
				segmentationToTs(configEntity.EndMp4+".2.mp4", filePath, "003")
			}

			titile := fileName
			var filePath1 string
			for i := 0; i < 100; i++ {
				_, filePath1 = ZipOf7Z1(titile, filePath, path+"/"+fileName, configEntity)
				if IsFile(filePath1) {
					fmt.Println(filePath1, " is mp4")
					break
				}
			}

			targetPath = path + "/" + fileName + ".3.mp4"
			for i := 0; i < 100; i++ {
				flg = CopyFfmpeg(filePath1, targetPath)
				if IsFile(targetPath) {
					fmt.Println(targetPath, " target is mp4")
					break
				}
			}

			//ZipOf7Z1(fileName+".2.mp4", filePath, filePath+"/"+fileName+".2.mp4", configEntity)
			//SysnthesisTsZipToMp4(fileName+".2.mp4", configEntity, filePath, path+"/"+fileName+".2.mp4")

			//flg, targetPath = CombTs(path, fileName, f.Name(), configEntity)
			//log.Println("CombTs target:", targetPath, flg)
			//if flg {
			//	for i := 0; i < 10; i++ {
			//		if !ValidateFileSize2(targetPath, configEntity, configEntity.FileMinSize) {
			//			flg, targetPath = CombTs(path, fileName, f.Name(), configEntity)
			//		} else {
			//			flg = false
			//			log.Println(targetPath, "file not exists")
			//			break
			//		}
			//
			//	}
			//}
			if flg {

				log.Println("targetPath:{}", targetPath)
				content := fmt.Sprintf(configEntity.HtmlContent, f.Name())
				txtPath := strings.ReplaceAll(targetPath, ".mp4", ".txt")
				flag, _ := WriterTxtTip(txtPath, content)
				if flag {
					paths = append(paths, fmt.Sprintf(configEntity.AuthSubmit, targetPath))
					//	os.Remove(source)
					write(targetPath, configEntity)
				}
			}

		}

	}
	return true, paths

}

func write(path string, configEntity entity.DownloadEntity) {
	var paths []string
	paths = append(paths, fmt.Sprintf(configEntity.AuthSubmit, path))
	WriteSend(paths, configEntity.AbsolutePath)
}

func segmentationToTs(mp4Path string, filePath string, before string) bool {
	err := ffmpeg_go.Input(mp4Path, ffmpeg_go.KwArgs{"hwaccel": "cuda"}).
		Output(filePath+"/"+before+"%03d.ts", ffmpeg_go.KwArgs{"c": "copy", "map": 0, "f": "segment", "segment_time": 1, "segment_format": "mpegts", "qscale": "0"}).OverWriteOutput().Run()

	if nil != err {
		log.Println(err)
		return false
	}
	return true
}

func CombTs(path string, path1 string, fielName string, config entity.DownloadEntity) (bool, string) {
	source := path + "/" + path1
	target := path + "/" + fielName + ".2.mp4"

	flag, filePath := WriterTxt(source)
	if flag {
		//cmd := exec.Command(config.FFmpeg,
		//	"-hwaccel", "cuda",
		//	"-f", "concat",
		//	"-safe", "0",
		//	"-i", filePath,
		//	"-bsf:a", "aac_adtstoasc",
		//	"-c:v", "libx264",
		//	"-crf", "0",
		//	"-preset", "veryfast",
		//	"-b:v", "20000k",
		//	"-vf", "scale=2048:-1",
		//	target,
		//	"-y")
		//
		//err := cmd.Run()
		//
		//if err != nil {
		//	log.Println(err)
		//	return false, target
		//
		//}
		//log.Println("target", target)
		//return true, target
		err := ffmpeg_go.Input(filePath, ffmpeg_go.KwArgs{"hwaccel": "cuda", "f": "concat", "safe": "0"}).
			Output(target, ffmpeg_go.KwArgs{"bsf:a": "aac_adtstoasc", "c:v": "libx264", "crf": "0", "preset": "veryfast", "b:v": "20000k", "vf": "scale=2048:-1"}).OverWriteOutput().Run()

		if err != nil {
			log.Println(err)
			return false, target
		}
		return true, target
	}
	return false, target
}

//func compress(path string, configEntity entity.DownloadEntity) {
//	index := strings.LastIndex(path, ".")
//	len := len(path)
//	path1 := path[0:index] + ".1." + path[index:len]
//	cmd := exec.Command(strings.TrimSpace(configEntity.FFmpeg), "-i", path, "-b", val, "-allowed_extensions", "ALL", "-i", strings.TrimSpace(responseEntity.M3u8), "-c", "copy", strings.TrimSpace(mkdirPath))
//}
